const BaseRest = require('./base.js');
/* 分销系统商户信息 */
module.exports = class extends BaseRest {
  // 所有的请求否必须登陆
  async __before(action) {
    try {
      this.userInfo = await this.ctx.session('userInfo');
    } catch (err) {
      this.userInfo = {};
    }

    // GET请求都必须登陆
    if (think.isEmpty(this.userInfo)) {
      this.ctx.status = 401;
      return this.ctx.fail(-1, '请登录后操作');
    }
  }

  // 查询用户信息
  async getAction() {
    // APP客户端只允许用户看自己的信息
    const userInfo = this.userInfo;
    if (think.isEmpty(userInfo)) {
      this.ctx.status = 401;
      return this.ctx.fail(-1, '请登录后操作');
    }

    let data;

    // 根据ID查询
    if (this.id) {
      // data = await this.modelInstance.where({ id: this.getId()}).fieldReverse('password,encrypt,last_login_ip,last_login_time').find();
      data = await this.modelInstance.where({ uid: this.id }).find();
      return this.success(data);
    }

    if (this.get('parents')) {
      data = await this.modelInstance.getParents(this.get('parents'));
      think.logger.debug(data);

      return this.success(data);
    }

    // 分页查找，需要验证更多的权限，是否能够列用户信息
    let map = {};

    // 查会员以及会员的关联信息
    if (this.get('members')) {
      map = { puid: this.get('members') };
    }

    // 页码
    const page = this.get('page') || 1;
    // 每页显示数量
    const pageSize = this.get('pageSize') || 5;
    data = await this.modelInstance.where(map).page(page, pageSize).order('create_time desc').setRelation('has_merchant', false).countSelect();

    return this.success(data);
  }

  async postAction() {
    const data = this.post();
    // 用户注册
    const user = await this.modelInstance.where({ username: data['username'] }).find();
    if (!think.isEmpty(user)) {
      return this.fail(-1, '用户名已经存在');
    }

    data['encrypt'] = think.service('utils').getRamdomString(10, {});
    data['password'] = think.service('utils').getEncryptPassword(data['password'], data['encrypt']);
    data['create_ip'] = this.ctx.ip;
    data['create_time'] = Math.round((new Date()).getTime() / 1000);
    const ret = await this.modelInstance.addUser(data);

    think.logger.debug(ret);
    return this.success(ret);
  }

  // 更新用户信息
  async putAction() {
    // 删除缓存
    think.cache('user', null);

    const userInfo = this.userInfo;
    const data = this.post();
    if (think.isEmpty(data)) {
      return this.fail(1000, '数据不能为空');
    }
    const rows = await this.modelInstance.where({ id: userInfo.id }).update(data);
    if (rows) {
      return this.success({ affectedRows: rows }, '更新成功');
    } else {
      return this.fail(1000, '更新失败');
    }
  }

  /**
   * 删除内容
   * @return {[type]} [description]
   */
  async deleteAction() {
    if (!this.id) {
      return this.fail(1001, '用户不存在');
    }
    // 软删除标志
    const rows = await this.modelInstance.where({ id: this.id }).update({ deleted_flag: 1 });
    if (rows) {
      await this.hook('userDelete', { id: this.id });
      return this.success({ affectedRows: rows }, '删除成功');
    } else {
      return this.fail(1000, '删除失败');
    }
  }
};
